const passport = require('passport')
const User = require('./mongoose')
const LocalStrategy = require('passport-local').Strategy
const createError = require('http-errors')
const jwt = require('jsonwebtoken')
const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy
const WechatStrategy = require('passport-wechat').Strategy

const { Strategy: JwtStrategy, ExtractJwt } = require('passport-jwt')

const opts = {}
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken()
opts.secretOrKey = '12345-67890-09876-54321'
passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
    User.findOne({ _id: jwt_payload._id }, (err, user) => {
        if (err) done(err, false)
        else if (user) done(null, user)
        else done(null, false)
    })
}))


passport.use(new LocalStrategy(User.authenticate()))
passport.use(new GoogleStrategy({
    clientID: '1082297206021-62hluo2o9nb25bbf50ffnuqlmn8h85si.apps.googleusercontent.com',
    clientSecret: 'ytsIcc3x2lcUcm2H7OeCdJmQ',
    callbackURL: "http://localhost:3000/auth/google/callback",
    
},
    (accessToken, refreshToken, profile, done) => {

    }
))
passport.use(new WechatStrategy({
    appID: 'wx9fd7e135baddde5a',
    appSecret: '4153d465fcba16636d136c24ab5fd306',
    client: 'web',
    callbackURL: "http://localhost:3000/auth/wechat/callback",
    scope: 'snsapi_base',
    state: '1',
},
    (accessToken, refreshToken, profile, done) => {

    }
))
// passport.serializeUser(User.serializeUser())
// passport.deserializeUser(User.deserializeUser())



exports.verifyUser = passport.authenticate('jwt', { session: false })
// exports.verifyUser = (req,res,next)=>{
//     if(req.user) next()
//     else next(createError(403))
// }

exports.getToken = (user) => {
    return jwt.sign(
        user,
        opts.secretOrKey,
        { expiresIn: 3600 }
    )
}
